import tests from './tests.js';

// 获取非进度条相关页面元素
const h1 = document.querySelector('h1');
const tag = document.querySelector('.tag');
const forget = document.querySelector('.forget');
const go = document.querySelector('.go');
const remember = document.querySelector('.remember');
const best = document.querySelector('.best');
const bestTime = document.querySelector('.best span');
const note = document.querySelector('.note');

let point;
let num;

// 用于从本地存储获取得分，处理类型转换及默认值情况
const getScoreFromLocalStorage = (testId, testType) => {
  const storedScore = localStorage.getItem(`${testId}-${testType}`);
  return storedScore ? parseInt(storedScore, 10) : 0;
};

// 用于更新本地存储的得分
const updateLocalStorageScore = (testId, testType, score) => {
  localStorage.setItem(`${testId}-${testType}`, score.toString());
};

// 进度条
const progress = () => {
  const step = document.querySelectorAll('.step')

  step.forEach((item, index) => {
    const idValue = parseInt(item.id, 10);
    if (!isNaN(idValue) && idValue <= point) {
      item.classList.add('completed');
    } else {
      item.classList.remove('completed');
    }
  })
}

const getTest = () => {
  // 重置point为0开始新题目展示
  point = 0;
  num = Math.floor(Math.random() * tests.length);
  h1.innerText = `${tests[num].title}`;
  tag.innerText = `${tests[num].type}`;

  // 获取对应题目之前存储的得分并赋值给point
  point = getScoreFromLocalStorage(tests[num].id, tests[num].type);

  // 根据得分情况处理最佳得分显示逻辑
  if (point > 4) {
    best.style.display = 'block';
    bestTime.innerText = point;
  } else {
    best.style.display = 'none';
  }

  progress()
};

getTest();



forget.addEventListener('click', () => {
  // 确保point不小于0
  point = Math.max(0, point - 1);
  updateLocalStorageScore(tests[num].id, tests[num].type, point);
  note.innerText = '-1';
  note.style.visibility = 'visible';
  setTimeout(() => {
    note.style.visibility = 'hidden';
  }, 1000);
  getTest();
});

go.addEventListener('click', () => {
  getTest();
});

remember.addEventListener('click', () => {
  point++;
  updateLocalStorageScore(tests[num].id, tests[num].type, point);
  note.innerText = '+1';
  note.style.visibility = 'visible';
  setTimeout(() => {
    note.style.visibility = 'hidden';
  }, 1000);
  getTest();
});

